/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.controller;

import com.bayu.services.dao.ListrikDao;
import com.bayu.services.entity.Listrik;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Bayu
 */
@Controller
@RequestMapping("/listrik-input.htm")
public class ListrikInput {
    ListrikDao listrikDao;

    @Autowired
    private void setListrikDao(ListrikDao listrikDao){
      this.listrikDao = listrikDao;
    }

    @RequestMapping(method = RequestMethod.GET)
    public void displayForm(ModelMap map,String id){

    }

    @RequestMapping(method = RequestMethod.POST)
    public String proccessForm(@ModelAttribute("Listrik") Listrik listrik , BindingResult result,ModelMap map, String bulan,HttpServletRequest req){
            DateFormat formarter = new SimpleDateFormat("yy-MM-dd");
            Date tgl;

            if(result.hasFieldErrors("bulan")){
                try {
                    tgl = formarter.parse(bulan);
                    listrik.setBulan(tgl);
                } catch (ParseException ex) {
                    Logger.getLogger(Listrik.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
                
               List total = this.listrikDao.custom("select count(*) from Listrik where bulan='"+bulan+"'");

            String strTotal=total.get(0).toString();


            int c = Integer.valueOf(strTotal).intValue();
            System.out.println(strTotal+"---"+c+"--"+bulan);
            if(c > 0){
                return "redirect:ErrorDuplicate.html";
            }else{
     
                 

                 this.listrikDao.save(listrik);
                 return "redirect:view-listrik-data.htm?msg=Data has been updated";
            }
                 

    }
}
